package com.hdu.careerplan.controller;

import com.hdu.careerplan.enums.StatusCode;
import com.hdu.careerplan.exception.WrongKeyInJwtException;
import com.hdu.careerplan.pojo.dto.EmployerLoginDTO;
import com.hdu.careerplan.pojo.dto.EmployerRegisterDTO;
import com.hdu.careerplan.pojo.dto.ScreenResumeDTO;
import com.hdu.careerplan.pojo.entity.Employer;
import com.hdu.careerplan.pojo.vo.QualifiedResumeVO;
import com.hdu.careerplan.pojo.vo.Result;
import com.hdu.careerplan.pojo.vo.ResultData;
import com.hdu.careerplan.pojo.vo.UserWholeInfoVO;
import com.hdu.careerplan.service.EmployerService;
import com.hdu.careerplan.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@CrossOrigin
@RequestMapping("/employer")
public class EmployeeController {

    @Resource
    private EmployerService employerService;

    /**
     * 员工注册
     * @param employerRegisterDTO
     * @param servletResponse
     * @return
     */
    @PostMapping("/account/register")
    public ResultData register(@RequestBody EmployerRegisterDTO employerRegisterDTO, ServletResponse servletResponse) {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        int register = employerService.register(employerRegisterDTO);

        if (register == 0) {
            EmployerLoginDTO employerLoginDTO = new EmployerLoginDTO();
            employerLoginDTO.setPhone(employerRegisterDTO.getPhone());
            employerLoginDTO.setPassword(employerRegisterDTO.getPassword());
            Employer loginEmployer = employerService.login(employerLoginDTO);
            if (loginEmployer != null) {
                Map<String, Object> claims = new HashMap<>();
                claims.put("employeeId", loginEmployer.getEmployerId());
                claims.put("phone", loginEmployer.getPhone());
                claims.put("code", loginEmployer.getCode());
                claims.put("authority", loginEmployer.getAuthority());
                String jwt = JwtUtil.generateJWT(claims);

                return Result.success(jwt);
            }
            response.setStatus(401);
            return Result.responseWithNonData(StatusCode.LOGIN_FAILED);
        } else {
            response.setStatus(401);
            return Result.responseWithNonData(StatusCode.REGISTER_FAILED);
        }
    }

    /**
     * 员工登录
     * @param employerLoginDTO
     * @param servletResponse
     * @return
     */
    @PostMapping("/account/login")
    public ResultData login(@RequestBody EmployerLoginDTO employerLoginDTO, ServletResponse servletResponse) {
        Employer loginEmployer = employerService.login(employerLoginDTO);
        if (loginEmployer != null) {
            Map<String, Object> claims = new HashMap<>();
            claims.put("employerId", loginEmployer.getEmployerId());
            claims.put("phone", loginEmployer.getPhone());
            claims.put("code", loginEmployer.getCode());
            claims.put("authority", loginEmployer.getAuthority());
            String jwt = JwtUtil.generateJWT(claims);

            return Result.success(jwt);
        }
        ((HttpServletResponse) servletResponse).setStatus(401);
        return Result.responseWithNonData(StatusCode.LOGIN_FAILED);
    }

    /**
     * 下载他人简历
     * @param usrId
     * @param servletRequest
     * @param servletResponse
     * @return
     */
    @GetMapping("/{id}/profile/attachment")
    public ResultData downloadResume(@PathVariable(name = "id") Long usrId, ServletRequest servletRequest, ServletResponse servletResponse) throws WrongKeyInJwtException {
        System.out.println(usrId);
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        Object employerId = JwtUtil.getInfoFromJWT(servletRequest, "employerId");
        File file = employerService.downloadResume(Long.valueOf(usrId.toString()), Long.valueOf(employerId.toString()));
        if (file == null) return Result.responseWithNonData(StatusCode.UNKNOWN_ERROR);
        response.reset();
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setContentLength((int) file.length());
        response.setHeader("Content-Disposition", "attachment;filename=" + file.getName() );

        try(BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));) {
            byte[] buff = new byte[1024];
            OutputStream os  = response.getOutputStream();
            int i = 0;
            while ((i = bis.read(buff)) != -1) {
                os.write(buff, 0, i);
                os.flush();
            }
        } catch (IOException e) {
            log.error("{}",e);
            return Result.responseWithNonData(StatusCode.UNKNOWN_ERROR);
        }


        return null;

    }

    /**
     * 获取他人信息
     * @param userId
     * @param servletRequest
     * @return
     */
    @GetMapping("/{id}/profile")
    public ResultData getUserCompletedInfo(@PathVariable(name = "id") Long userId, ServletRequest servletRequest) throws WrongKeyInJwtException {
        Object employerId = JwtUtil.getInfoFromJWT(servletRequest, "employerId");
        UserWholeInfoVO userInfo = employerService.getUserInfoById(userId, Long.valueOf(employerId.toString()));
        if (userInfo == null) return Result.responseWithNonData(StatusCode.NO_CONTENT);
        else return Result.responseWithData(StatusCode.SUCCESS, userInfo);

    }

    @GetMapping("/qualified")
    public ResultData screenResume(ScreenResumeDTO screenResumeDTO, ServletRequest servletRequest) throws WrongKeyInJwtException {
        Object employerId = JwtUtil.getInfoFromJWT(servletRequest, "employerId");
        QualifiedResumeVO qualifiedResumeVO = employerService.screenResume(screenResumeDTO, Long.valueOf(employerId.toString()));
        if (qualifiedResumeVO == null) return Result.responseWithNonData(StatusCode.NO_CONTENT);
        return Result.responseWithData(StatusCode.SUCCESS, qualifiedResumeVO);
    }



}
